package org.example.algo;

import java.util.Arrays;

/**
 * @author shenguangyang
 */
public class N02_InsertSort {
    public static void main(String[] args) {
        int[] arr = {10, 1, 6, 9, 11, 0, 12, 5, 7, 8};
        insertSort(arr);
        System.out.println(Arrays.toString(Arrays.stream(arr).toArray()));
    }

    public static void insertSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }

        int N = arr.length;
        for (int i = 0; i < N; i++) {
            int curIndex = i, preIndex = i - 1;
            while (preIndex >= 0 && (arr[curIndex]) < arr[preIndex]) {
                swap(arr, curIndex, preIndex);
                curIndex--;
                preIndex--;
            }
        }
    }

    public static void swap(int[] arr, int v1Index, int v2Index) {
        int temp = arr[v1Index];
        arr[v1Index] = arr[v2Index];
        arr[v2Index] = temp;
    }
}
